package com.yidao.user.service.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import com.yidao.core.service.impl.BaseDomainObjectServiceImpl;
import com.yidao.user.domain.User;
import com.yidao.user.service.AuthenticationException;
import com.yidao.user.service.UserService;

public class UserServiceImpl extends BaseDomainObjectServiceImpl<User> implements UserService{
	
	@Override
	@Transactional
	public void authenticate(String username, String password)
			throws AuthenticationException {
		Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
		List<User> users = session.createCriteria(User.class)
									.add(Restrictions.eq("username", username))
									.add(Restrictions.eq("password", password))
									.add(Restrictions.eq("status", 1))
									.list();
		if(users == null || users.size() != 1){
			throw new AuthenticationException(1);
		}
	}
	
	@Override
	@Transactional
	public User getByUserName(String loginName) {
		Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
		User user = (User)session.createCriteria(User.class)
									.add(Restrictions.eq("username", loginName))
									.add(Restrictions.eq("status", 1))
									.uniqueResult();
		return user;
	}

	@Override
	@Transactional
	public void changePassword(String userName, String oldPassword, String newPassword) 
			throws AuthenticationException {
		
		User user = this.getByUserName(userName);
		
		if(!oldPassword.equals(user.getPassword())){
			throw new AuthenticationException(1);
		}
		user.setPassword(newPassword);
	}
}
